<template>
	<view class="container">
		<view class="list padding30">
			<view class="item" v-for="(item, index) in list" :key="index">
				<view class="row acea-row row-between-wrapper">
					<text>配送单号</text>
					<text>{{ item.order_id }}</text>
				</view>
				<view class="row acea-row row-between-wrapper">
					<text>{{ item.add_time }}</text>
					<text style="color: #D9001B;">{{item.status == 0 ? '待领取' : '已领取'}}</text>
				</view>
				<view class="row acea-row row-between-wrapper">
					<text>转赠{{ item.number }}次</text>
				</view>
				<view class="foot acea-row row-right">
					<view class="btn" v-if="item.status == 0" @click="confirm(item)">重新转赠</view>
					<view class="qs-btn" v-else>已转赠</view>
				</view>
			</view>
			<view class="empty acea-row row-column row-middle" v-if="list.length == 0">
				<image src="/static/images/empty-box.png" mode="aspectFit"></image>
				<text>您还没有赠送记录哦!</text>
			</view>
			<view class="nomore acea-row row-column row-middle" v-if="status == 'nomore' && list.length > 0">
				没有更多了
			</view>
		</view>
		
		<view class="poster-pop" v-if="posterImageStatus">
			<!-- #ifdef H5 -->
			<img :src="posterImage" mode="widthFix"></img>
			<!-- #endif -->
			<!-- #ifdef MP -->
			<image :src="posterImage" mode="widthFix" @longpress="longpress"></image>
			<!-- #endif -->
			<view class="close" @click="posterImageClose"></view>
		</view>
		<canvas class="canvas" canvas-id="myCanvas" v-if="canvasStatus"></canvas>
		<view class="mask" v-if="posterImageStatus"></view>
	</view>
</template>

<script>
	import { giftList, orderTransfer } from '@/api/order.js'
	import { HTTP_REQUEST_URL } from '@/config/app.js';
	export default {
		data() {
			return {
				list: [],
				page: 1,
				limit: 15,
				status: 'loading',
				posterImage: '',
				canvasStatus: false, //海报绘图标签
				posterImageStatus: false,
			};
		},
		onLoad() {
			this.getList()
		},
		methods: {
			// 获取列表数据
			getList() {
				if(this.status == 'nomore') return;
				giftList({
					page: this.page,
					limit: this.limit
				}).then(res => {
					this.list = this.list.concat(res.data)
					if(res.data.length < this.limit) {
						this.status = 'nomore'
					}
				})
			},
			// 重新转赠
			async confirm(item) {
				let that = this
				uni.showLoading({
					title: '海报生成中...'
				})
				that.$set(that, 'canvasStatus', true);
				orderTransfer({
					shippingIds: item.shipping_ids, // 选择转赠的订单id，多个逗号分隔
					orderId: item.order_id, // 主订单id
					re: 1
				}).then(async res => {
					if(res.status == 200) {
						let Img, arr2;
						if(HTTP_REQUEST_URL == 'https://flohy.ming.net.cn') {
							Img = 'https://flohy.ming.net.cn/uploads/attach/2021/12/20211214/bd207800eeb78577ab127776c200bcd9.png';
						} else {
							Img = 'https://pro.ming.net.cn/uploads/attach/2021/12/20211211/389d67fd53b438b66af62351783ae95a.png';
						}
						let qrCode = res.data.code;
						// #ifdef H5
						arr2 = [
							qrCode, 
							await this.downloadFilestoreImage(Img)
						];
						// #endif
						// #ifdef MP
						arr2 = [
							await this.base64ToSave(qrCode), 
							await this.downloadFilestoreImage(Img)
						];
						// #endif
						this.$util.orderPosterCanvas(arr2, (tempFilePath) => {
							that.$set(that, 'canvasStatus', false);
							that.$set(that, 'posterImage', tempFilePath);
							that.$set(that, 'posterImageStatus', true);
							
							// #ifdef MP
							that.removeSave()
							// #endif
							uni.hideLoading();
						});
						
					} else {
						uni.hideLoading();
						this.$util.Tips({
							title: res.msg
						});
					}
				})
			},
			//隐藏海报
			posterImageClose: function() {
				this.posterImageStatus = false;
			},
			//图片转符合安全域名路径
			downloadFilestoreImage(url) {
				return new Promise((resolve, reject) => {
					let that = this;
					uni.downloadFile({
						url: url,
						success: function(res) {
							resolve(res.tempFilePath);
						},
						fail: function() {
							return that.$util.Tips({
								title: ''
							});
						}
					});
				})
			},
			base64ToSave (base64data,FILE_BASE_NAME) {
				FILE_BASE_NAME = 'tmp_base64src' + Math.random(0, 10000000000) // 随机数避免缓存问题
				const fsm = uni.getFileSystemManager();
				return new Promise((resolve, reject) => {
					//format这个跟base64数据的开头对应
					const [, format, bodyData] = /data:image\/(\w+);base64,(.*)/.exec(base64data) || [];
					if (!format) {
						reject(new Error('ERROR_BASE64SRC_PARSE'));
					}
					const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
					const buffer = wx.base64ToArrayBuffer(bodyData);
					fsm.writeFile({
						filePath,
						data: buffer,
						encoding: 'binary',
						success() {
							resolve(filePath);
						},
						fail() {
							reject(new Error('ERROR_BASE64SRC_WRITE'));
						},
					});
				});
			},
			removeSave(FILE_BASE_NAME='tmp_base64src',format='jpg') {
				return new Promise((resolve)=>{
					// 把文件删除后再写进，防止超过最大范围而无法写入
					const fsm = uni.getFileSystemManager();  //文件管理器
					const FILE_BASE_NAME = 'tmp_base64src';
					const format = 'jpg';
					const filePath = `${wx.env.USER_DATA_PATH}/${FILE_BASE_NAME}.${format}`;
					fsm.unlink({
						filePath: filePath,
						success(res) {
							console.log('文件删除成功');
						},
						fail(e){
							console.log('readdir文件删除失败：',e)
						}
					});
				})
			
			},
			// 长按保存
			longpress() {
				let that = this;
				// #ifdef MP
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.writePhotosAlbum']) {
							uni.authorize({
								scope: 'scope.writePhotosAlbum',
								success() {
									uni.saveImageToPhotosAlbum({
										filePath: that.posterImage,
										success: function(res) {
											that.posterImageClose();
											that.$util.Tips({
												title: '保存成功',
												icon: 'success'
											});
										},
										fail: function(res) {
											that.$util.Tips({
												title: '保存失败'
											});
										}
									});
								}
							});
						} else {
							uni.saveImageToPhotosAlbum({
								filePath: that.posterImage,
								success: function(res) {
									that.posterImageClose();
									that.$util.Tips({
										title: '保存成功',
										icon: 'success'
									});
								},
								fail: function(res) {
									that.$util.Tips({
										title: '保存失败'
									});
								}
							});
						}
					}
				});
				// #endif
			}
		},
		onReachBottom() {
			this.page++
			this.getList()
		}
	}
</script>

<style lang="scss">
page {
	background-color: #fff;
}
.list {
	border-top: 1px solid #f9f9f9;
	.item {
		width: 100%;
		border: 1px solid #eee;
		border-radius: 10rpx;
		padding: 10rpx 30rpx;
		margin-bottom: 30rpx;
		.row {
			width: 100%;
			padding: 20rpx 0;
			border-bottom: 1px solid #eee;
		}
		.foot {
			padding: 20rpx 0;
			.btn, .qs-btn {
				width: 150rpx;
				height: 50rpx;
				line-height: 50rpx;
				background-color: #9AC83A;
				color: #fff;
				border-radius: 8rpx;
				text-align: center;
				font-size: 28rpx;
			}
			.qs-btn {
				background-color: #D7D7D7;
				color: #7F7F7F;
			}
		}
	}
}
.empty {
	padding-top: 100rpx;
	color: #999;
	image {
		width: 80%;
	}
}
.canvas {
	position: absolute;
	bottom: 100%;
	width: 505px;
	height: 759px;
}
.poster-pop {
	width: 505rpx;
	height: 759rpx;
	position: fixed;
	left: 50%;
	z-index: 399;
	top: 40%;
	// margin-top: -357rpx;
	transform: translate(-50%, -50%);
	animation: centerToHeight 0.25s linear;
	.close {
		position: absolute;
		bottom: -120rpx;
		left: 50%;
		transform: translate(-50%);
		z-index: 99;
		width: 100rpx;
		height: 100rpx;
		background: url('/static/images/poster_close.png') no-repeat center;
		background-size: 70%;
	}
}
@keyframes centerToHeight {
	0% {transform: translate(-50%, 100%);}
	100%{transform: translate(-50%, -50%);}
}
.poster-pop img,
.poster-pop image {
	width: 100%;
	height: 100%;
	display: block;
}
.mask {
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	bottom: 0;
	background-color: rgba(0, 0, 0, 0.6);
	z-index: 300;
	animation: centerToHeight1 0.25s linear;
}
@keyframes centerToHeight1 {
	from {opacity: 0;}
	to {opacity: .6;}
}
</style>
